#!/usr/local/bin/python3
# -*- coding: UTF-8 -*-
"""
@author:apple
@file:demo03.py
@time:2022/03/18
"""
import asyncio
import aiohttp
from lxml import etree

headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.51 Safari/537.36"
}


# async def
# https://movie.douban.com/chart
async def get_movie_list():
    ...
    url = "https://movie.douban.com/top250?start=0"
    # //*[@id="content"]/div/div[1]/ol/li[13]/div/div[2]/div[1]/a/@href
    async with aiohttp.ClientSession(headers=headers) as session:
        ...
        async with session.get(url) as response:
            html = await response.text()
        print(html)
        xpath_html = etree.HTML(html)

        return xpath_html.xpath('//*[@id="content"]/div/div[1]/ol/li/div/div[2]/div[1]/a/@href')


async def get_movie_content(url):
    ...
    async with aiohttp.ClientSession(headers=headers) as session:
        ...
        async with session.get(url) as response:
            ...
            html = await response.text()
        xpath_html = etree.HTML(html)
        result = "".join(xpath_html.xpath('//*[@id="content"]/h1/span[1]/text()'))
        # print(result)
        return "bac"


async def main():
    ...
    # movie_list = await get_movie_list()
    movie_list = ["https://www.baidu.com/","https://www.baidu.com/"]
    print(movie_list)

    if len(movie_list) == 0:
        return

    tasks = []
    for val in movie_list:
        ...
        tasks.append(asyncio.create_task(get_movie_content(val)))
        # tasks.append(asyncio.ensure_future(get_movie_content(val)))

    dones, pendings = await asyncio.wait(tasks)

    # for lastTask in asyncio.as_completed(tasks):
    #     res = await lastTask
    #     print(res)
    # loop = asyncio.get_running_loop()
    # loop.run_until_complete(asyncio.gather(*tasks))

    for task in dones:
        print(task.result())
    # print(dones)


if __name__ == '__main__':
    pass
    asyncio.run(main())
